package com.iqiao.common.util.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.bson.types.ObjectId;

import java.io.IOException;

public class GsonFactory {

    public static Gson newInstance(){
        GsonBuilder builder = new GsonBuilder();

        builder.registerTypeAdapter(ObjectId.class,
                new TypeAdapter<ObjectId>() {
                    @Override
                    public ObjectId read(JsonReader reader) throws IOException {
                        if (reader.peek() == JsonToken.NULL)
                        {
                            reader.nextNull();
                            return null;
                        }

                        String nextString = reader.nextString();
                        return "null".equals(nextString)?
                                null: new ObjectId(nextString);
                    }

                    @Override
                    public void write(JsonWriter writer, ObjectId id)
                            throws IOException
                    {
                        if (id == null)
                        {
                            writer.nullValue();
                            return;
                        }

                        writer.value(id.toString());
                    }
                });
        return builder.create();
    }
}
